<template>
  <div v-if="isDetail">
    <div v-if="remarkList.length">
      <div v-for="(item,index) in remarkList" :key="index" class="test">
        <el-tooltip :open-delay="800" placement="top-start" effect="dark">
          <div slot="content" style="max-width:300px;  overflow:auto; min-width:200px; max-height:300px">
            <div style="max-width:300px" v-html="handleRemark(item.content,index)" />
          </div>
          <div class="ellipsisOne" style="max-width:300px" v-html="handleRemark(item.content,index)" />
        </el-tooltip>
      </div>
    </div>
    <div v-else>--</div>
  </div>
  <div v-else>
    <div :class="{'mobile-wrap':showMobilePage}">
      <div v-for="(item,index) in remarkList" :key="index" class="remark-item">
        <div :class="{'mobile-item':showMobilePage}" class="item">
          <el-input
            v-if="!isAdd"
            v-model="item.content"
            :class="{'is-error':errIds.includes(item._uuid)}"
            :placeholder="item.placeholder"
            class="input-with-select"
            resize="none"
            size="small"
            maxlength="200"
            @select="handleSelect($event, index, item)">
            <el-select slot="prepend" v-model="item.type" :disabled="!isAdd && isEditQuestion" :class="{'select-disabled':!isAdd && isEditQuestion}" @change="changeType($event, item)">
              <el-option v-for="(ele, ind) in typeList" :key="ind" :label="ele.label" :value="ele.value" />
            </el-select>
          </el-input>
          <el-autocomplete
            v-else
            v-model="item.content"
            :fetch-suggestions="(content, cb) => querySearch(content, cb, item.type)"
            :trigger-on-focus="false"
            :popper-append-to-body="true"
            :placeholder="item.placeholder"
            size="small"
            popper-class="remark-autocomplete"
            @select="handleSelect($event, index, item)">
            <el-select slot="prepend" v-model="item.type" placeholder="请选择" @change="changeType($event, item)">
              <el-option v-for="(ele, ind) in typeList" :key="ind" :label="ele.label" :value="ele.value" />
            </el-select>
          </el-autocomplete>
          <span v-if="!isDetail && showMobilePage && isAdd" class="btn mobile-del" @click="toDelete(index)">删除</span>
          <el-checkbox v-if="isAdd && item.type !== 4" v-model="item.required" :false-label="0" :true-label="1" class="ml16 box">必填</el-checkbox>
          <el-checkbox v-if="isAdd" v-model="item.highlight" :false-label="0" :true-label="1" class="ml16 box">高亮</el-checkbox>
          <span v-if="!isDetail && !showMobilePage && isAdd" class="ml16 btn del" @click="toDelete(index)">删除</span>
        </div>
        <div v-if="[2,3].includes(item.type) && item.selectList" class="mb12">
          <div class="select-title">
            <span class="title"><span class="red-text">*</span>选项及默认值</span>
            <div class="line-border" />
            <span class="blue-text select-add" @click="addSelect(item)">添加选项</span>
            <div class="line-border" />
            <span class="blue-text select-edit" @click="openBatchEdit(item)">批量编辑</span>
          </div>
          <div v-for="(ele, ind) in item.selectList" :key="ind" class="select-box">
            <div class="select-box-border" />
            <el-input v-model="ele.label" :class="{'is-error':errIds.includes(ele._uuid)}" size="small" class="width240" maxlength="200"/>
            <el-checkbox v-if="isAdd" v-model="ele.allowRemark" :false-label="0" :true-label="1" class="m10 box">允许备注</el-checkbox>
            <span v-if="item.selectList.length > 1" :style="!isAdd?'margin-left:10px':''" class="btn del" @click="deleteSelect(ind, item)">删除<tipIcon v-if="isAdd" style="position: relative;top: 2px;left: 4px;" content="仅删除本次询单的选项" /></span>
          </div>
        </div>
      </div>
    </div>
    <div v-if="isAdd" class="flex">
      <div><span :style="{marginLeft:isAdditional?'16px':'0'}" :class="{'mobile-add':showMobilePage}" class="btn" style="margin-right: 8px;" @click="addItem()">添加问题+</span></div>
      <div class="line-border" />
      <div><span :style="{marginLeft:isAdditional?'16px':'0'}" :class="{'mobile-add':showMobilePage}" class="btn" @click="handleBatchAdd">批量新增+</span></div>
    </div>
    <BatchEditDialog ref="batchEditDialog" @handleSaveBatchEdit="handleSaveBatchEdit"/>
  </div>
</template>
<script>
import BatchEditDialog from './batchEditDialog.vue';
import { handleRemark } from './tool';
import { mapState } from 'vuex';
import { generateUUID } from '@/utils/tools';
import ElMessage from '@/utils/message';
import { queryQuestionHistory } from '@/api/flyNotice';

export default {
  components: { BatchEditDialog },
  directives: {
    inputFocus: {
      inserted(el, binding) {
        if (binding.value) {
          el.querySelector('.el-textarea__inner').focus();
        }
      }
    }
  },
  props: {
    remarkList: {
      type: Array,
      default: () => []
    },
    isDetail: {
      type: Boolean,
      default: false
    },
    isAdditional: {
      type: Boolean,
      default: false
    },
    isAdd: { // 是否能够增加问题
      type: Boolean,
      default: true
    },
    isEditQuestion: { // 是否为编辑问题
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      errIds: [],
      typeList: [
        { label: '问答题', value: 0 },
        { label: '是非题', value: 1 },
        { label: '多选题', value: 2 },
        { label: '单选题', value: 3 },
        { label: '仅描述', value: 4 },
        { label: '图片题', value: 5 }
      ],
      batchType: 0, // 0-批量新增问题,1-批量编辑选项
      batchItem: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  methods: {
    handleRemark,
    validate() {
      const errArr = [];
      this.remarkList.forEach(item => {
        if (!item.content) {
          errArr.push(item._uuid);
        }
        if ([2, 3].includes(item.type)) {
          item.selectList.forEach(ele => {
            if (!ele.label) {
              errArr.push(ele._uuid);
            }
          });
        }
      });
      this.errIds = errArr;
      if (errArr.length) {
        const temp = !this.isAdd ? '问题名称及选项' : (this.isAdditional ? '追加说明' : '特殊备注');
        this.$message.warning(`请检查${temp}是否填写完整`);
        return false;
      }
      return true;
    },
    clearError() {
      this.errIds = [];
    },
    inputBlur() {
      this.errIds = [];
    },
    addItem() {
      this.$emit('addItem');
    },
    toDelete(index) {
      this.$emit('toDelete', index);
    },
    getTypePlaceholder(val) {
      return {
        0: '用户可输入回复该问题',
        1: '用户选择是/否，选择否可输入备注回复该问题',
        2: '用户可选择预设的选项快速回复该问题，同时支持配置允许备注',
        3: '用户可选择预设的选项快速回复该问题，同时支持配置允许备注',
        4: '仅展示，用户无需回复该问题',
        5: '用户可上传图片回复该问题'
      }[val];
    },
    changeType(val, item) {
      if (val === 4) {
        item.required = 0;
      }
      item.placeholder = this.getTypePlaceholder(val);
      if ([2, 3].includes(val)) {
        item.selectList = [
          { label: '选项1', _uuid: generateUUID() },
          { label: '选项2', _uuid: generateUUID() },
          { label: '选项3', _uuid: generateUUID() }
        ];
      }
    },
    addSelect(item) {
      // 【v3.3.8】取消最多12个的限制
      const len = item.selectList.length + 1;
      item.selectList.push({ label: `选项${len}`, _uuid: generateUUID() });
    },
    deleteSelect(ind, item) {
      item.selectList.splice(ind, 1);
    },
    handleBatchAdd() {
      this.batchType = 0;
      this.batchItem = [];
      this.$refs['batchEditDialog'].initData('', 0);
    },
    openBatchEdit(item) {
      this.batchType = 1;
      this.batchItem = item;
      // 将原有选项结果换行显示给编辑框
      const temp = item.selectList.map(item => {
        return item.label;
      }).join('\n');
      this.$refs['batchEditDialog'].initData(temp, 1);
    },
    handleSaveBatchEdit(batchContent) {
      let arr = batchContent.split(/[\n]/);
      if (arr && arr.length) {
        const len = arr.length;
        let msg = '';
        if (!this.batchType && (this.remarkList.length + len) > 50) {
          msg = '最多可添加50个问题';
        }
        if (msg) {
          ElMessage.warning(msg);
          return;
        }
      }
      if (arr && arr.length) {
        if (this.batchType) {
          const len = this.batchItem.selectList.length;
          if (arr.length < len) {
            // 编辑后的选项数量小于原来的选项数量,则先将原来的选项删掉至编辑后的数量
            this.batchItem.selectList = this.batchItem.selectList.slice(0, arr.length);
          }
          for (let i = 0; i < arr.length; i++) {
            if (!this.batchItem.selectList[i]) {
              // 编辑后的选项数量大于原来的选项数量,需要手动将新增的选项赋值为{}
              this.$set(this.batchItem.selectList, i, {});
            }
            // 编辑后的选项数量大于/小于/等于,都需要将编辑后的选项赋值给原来的选项
            this.$set(this.batchItem.selectList, i, { label: arr[i], _uuid: generateUUID() });
          }
        } else {
          // 特殊备注只有新增
          const start = this.remarkList.length;
          arr = arr.map(item => {
            return {
              type: 0,
              autofocus: true,
              _uuid: generateUUID(),
              required: 1,
              content: item,
              placeholder: '用户可输入回复该问题',
              selectList: []
            };
          });
          this.remarkList.splice(start, 0, ...arr);
        }
      }
    },
    handleSelect(val, index, item) {
      this.remarkList.splice(index, 1, { ...item, ...val });
    },
    querySearch(content, cb, type) {
      const params = {
        size: 5,
        content,
        type
      };
      queryQuestionHistory(params).then(res => {
        let result = [];
        if (res.data && res.data.items && res.data.items.length) {
          res.data.items.forEach(it => {
            it.value = it.content;
          });
          result = res.data.items.slice(0, 5);
        }
        cb(result);
      }).catch(err => console.error(err.message));
    }
  }
};
</script>
<style lang="scss" scoped>
.remark-item {
  &:last-child {
    .item {
      margin-bottom: 6px;
    }
  }
}
  .item{
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    &::v-deep {
      .el-autocomplete {
        width: 100%;
        .el-input-group__prepend {
          width: 90px;
          color: #333;
          background-color: transparent;
        }
      }
    }
  }
  .select-disabled {
    background-color: #f5f7fa;
    border-color: #e4e7ed;
    color: #c0c4cc;
  }
  .mobile-add {
    font-weight: bold;
  }
  .border-left {
    position: relative;
    padding-left:12px;
    margin-left: 12px;
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      margin-top: -7px;
      width: 1px;
      background: #ddd;
      height: 14px;
    }
  }
  .reamrk-width {
    width: 800px;
    &::v-deep {
      .el-select {
        width: 800px;
      }
      .el-input__inner {
        width: 800px;
      }
      .el-textarea__inner{
        height: 48px;
      }
    }
  }
  .input-with-select{
    &::v-deep .el-input-group__prepend {
      width: 90px;
      background-color: #fff;
      color: #333;
      .el-input__inner {
        border: none;
      }
    }
  }
  .select-container {
    margin-bottom: 12px;
  }
  .select-box {
    margin-left: 22px;
    position: relative;
    .select-box-border {
      position: absolute;
      left: -16px;
      width: 1px;
      height: 100%;
      border-left: 2px solid #dde1ea;
    }
    &:last-of-type {
      height: 32px;
    }
    .select-box-border::before {
      position: absolute;
      left: 8px;
      top: 14px;
      content: '';
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background: #AEB6C7;
    }
    ::v-deep {
      .el-input {
        margin: 0 0 10px 8px;
      }
    }
  }
  .mobile-wrap {
    .mobile-item {
      flex-wrap: wrap;
      ::v-deep {
        .el-input-group__prepend {
          padding: 0 !important;
          .el-select {
            margin: 0 !important;
          }
        }
      }
    }
    .select-box:last-of-type {
      height: unset !important;
    }
  }
  .width240 {
    width: 240px;
  }
  .select-title {
    display: flex;
    align-items: center;
    margin: -6px 0 6px;
    .title {
      margin-right: 8px;
    }
    .red-text {
      color: #FF4E5F;
    }
    .blue-text {
      color: #406EFF;
      cursor: pointer;
    }
    .line-border {
      height: 14px;
      border-left: 1px solid #ccc;
    }
    .select-add {
      margin: 0 8px;
    }
    .select-edit {
      margin-left: 8px;
    }
  }
  .is-error{
    &::v-deep {
      .el-input__inner {
        border-color: red !important;
      }
      .el-textarea__inner{
        border-color: red !important;
      }
    }
  }
  .btn, .link, .del{
    font-size: 14px;
    cursor: pointer;
    white-space: nowrap;
    margin-right: 8px;
  }
  .btn, .link{
    color: #406EFF;
  }
  .del{
    color: #192452;
  }
  .mobile-del {
    color: #FF4E5F;
    margin: 0;
  }
  .ml16{
    margin:0 0 0 16px;
  }
  .m10 {
    margin: 0 10px 0;
  }
  .true{
    margin: 0 0 0 12px;
  }
  .box{
    &::v-deep {
      .el-checkbox__label{
        padding-left: 4px;
      }
    }
  }
  .link{
    width: 240px;
  }
  .link-name {
    color: #406eff;
    font-weight: 500;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    img {
      width: 12px;
      position: relative;
      top: 1px;
      margin-left: 3px;
    }
  }
  .flex {
    .line-border {
      height: 14px;
      margin: 9px 8px 0 4px;
      border-left: 1px solid #ccc;
    }
  }
</style>

